package com.hzlj.position.locate.common.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fz.common.base.core.JsonUtils;
import com.fz.common.base.enums.CoordinateType;
import com.fz.common.base.exception.PubException;
import com.hzlj.position.config.common.dto.common.PositionAddDTO;
import com.hzlj.position.locate.common.dto.position.PositionAddResultDTO;
import lombok.extern.slf4j.Slf4j;

/**
 * e
 *
 * @author lifh
 * @date 2023/10/24 15:57
 **/
@Slf4j
public class PositionRestUtil {
    private final static String URI = "/position/locate";

    public static PositionAddResultDTO add(CoordinateType type,
                                           String url,
                                           PositionAddDTO position) {
        //坐标转换
        String[] lonlat = type.toWGS84(position.getLongitude(), position.getLatitude());
        position.setLongitude(lonlat[0]);
        position.setLatitude(lonlat[1]);
        log.info("发送定位数据:position={}", JsonUtils.obj2json(position));
        HttpRequest request = HttpRequest.put(url + URI)
                .body(JsonUtils.obj2json(position));
        try (HttpResponse execute = request.execute()) {
            String body = execute.body();
            PositionAddResultDTO result = JsonUtils.json2obj(body, PositionAddResultDTO.class);
            if (!result.isSuccess()) {
                log.error("发送定位数据失败:position={},result={}", position, result);
                throw new PubException(result.getCode(), result.getMsg());
            }
            return result;
        } catch (PubException e) {
            throw e;
        } catch (Exception e) {
            log.error("发送定位数据失败：position={}", position, e);
            throw new PubException("发送定位数据失败");
        }
    }


}
